package com.kexuexiong.demo.bear.common.config;

import org.apache.logging.log4j.util.Strings;
import org.apache.rocketmq.spring.support.DefaultRocketMQListenerContainer;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.annotation.Configuration;

@Configuration
public class EnvironmentIsolationConfig implements BeanPostProcessor {

    @Value("${rocketmq.enhance.enabledIsolation:true}")
    private Boolean enabledIsolation;

    @Value("${rocketmq.enhance.environment:''}")
    private String environment;

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        if (bean instanceof DefaultRocketMQListenerContainer) {
            DefaultRocketMQListenerContainer container = (DefaultRocketMQListenerContainer) bean;

            if (enabledIsolation && Strings.isNotBlank(environment)) {
                container.setTopic(String.join("_", container.getTopic(), environment));
            }
            return container;
        }
        return bean;
    }
}
